<script setup lang="ts">
import { loginAPI } from "@/apis/user";
import { FORMDATA_KEY } from "@/constants";
import { useUserStore } from "@/stores/user";
import { request } from "@/utils/reuqest";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";

// 写需求黄金思路：看需求，"从静到动"，先标签样式，后 TS 和逻辑，最后与后台交互，结果反馈
// 多做不同的需求，多积累语法使用经验，多积累解决方案，多解决 BUG，即可独当一面！

const formData = reactive({
  username: "",
  password: "",
});

// 表单校验规则
const formDataRlus = reactive<FormRules<typeof formData>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20个字符", trigger: "blur" },
  ],
});

// 表单实例
const formRef = ref<FormInstance>();
// 是否记住密码
const isRemember = ref(false);
// 是否同意协议
const isAgree = ref(false);

// 侦听数据变化
watch([isRemember, isAgree], ([val1, val2]) => {
  // 持久化存储
  localStorage.setItem("isRemember", String(val1));
  localStorage.setItem("isAgree", String(val2));
});

// 组件挂载时
onMounted(() => {
  // 获取本地数据，初始化，注意：本地存储保存的是字符串
  isRemember.value = localStorage.getItem("isRemember") === "true";
  isAgree.value = localStorage.getItem("isAgree") === "true";
  // 如果是记住密码
  if (isRemember.value) {
    // 获取本地数据
    const formDataStr = localStorage.getItem(FORMDATA_KEY);
    if (formDataStr) {
      // 解析数据
      const data = JSON.parse(formDataStr);
      // 回显到表单上
      formData.username = data.username;
      formData.password = data.password;
    }
  }
});

// 路由器，注意写到 setup 第一级，否则无法正常获取
const router = useRouter();
// 提交表单
const onSubmit = () => {
  // 校验用户是否勾选协议
  if (!isAgree.value) {
    return ElMessage({
      message: "请勾选用户协议",
      type: "error",
      duration: 1000,
    });
  }
  // 提交表单时统一校验
  formRef.value?.validate(async (valid) => {
    // 校验通过，才做登录
    if (valid) {
      // 实现登录业务
      const res = await loginAPI(formData);
      // 是否需要记住密码
      if (isRemember.value) {
        // 持久化存储
        localStorage.setItem(FORMDATA_KEY, JSON.stringify(formData));
      } else {
        // 没有记住密码就删除本地数据
        localStorage.removeItem(FORMDATA_KEY);
        // 清空表单数据
        formData.username = "";
        formData.password = "";
      }

      // 获取 store
      const store = useUserStore();
      // 把 token 存储到 store 和 cookie 中
      store.setToken(res.data.token);
      // 成功提示
      ElMessage({ message: "登录成功", type: "success" });
      // 替换到首页
      router.replace("/");
    }
  });
};

const onTest = async () => {
  const res = await request("/system/user/dropList");
  console.log(res);
};
</script>

<template>
  <div class="login_body">
    <div class="bg" />
    <div class="box">
      <div class="title">智慧园区-登录</div>
      <el-form ref="formRef" :model="formData" :rules="formDataRlus">
        <el-form-item label="账号" prop="username">
          <el-input v-model="formData.username" clearable autocomplete="on" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="formData.password"
            clearable
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="isRemember">记住我</el-checkbox>
          <el-checkbox v-model="isAgree">请勾选用户协议</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login_btn" @click="onSubmit">
            登录
          </el-button>
        </el-form-item>
      </el-form>
      {{ formData }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login_body {
  display: flex;
}

.bg {
  width: 60vw;
  height: 100vh;
  background: url("@/assets/login-bg.svg") no-repeat;
  background-position: right top;
  background-size: cover;
}

.box {
  margin: 200px 10% 0;
  flex: 1;

  .title {
    padding-bottom: 76px;
    font-size: 26px;
    font-weight: 500;
    color: #1e2023;
  }

  ::v-deep() {
    .ant-form-item {
      display: flex;
      margin-bottom: 62px;
      flex-direction: column;
    }

    .ant-form-item-label label {
      font-size: 16px;
      color: #8b929d;
    }

    .ant-input,
    .ant-input-password {
      border-radius: 8px;
    }
  }
}

.login_btn {
  width: 100%;
}
</style>